package com.android.systemui.statusbar.board;

import android.content.Context;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.PopupWindow;
import android.app.Dialog;

import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.content.DialogInterface;
import android.view.View.OnClickListener;

import com.android.systemui.R;

public abstract class BaseDialog {

    public static BaseDialog sCurrentShowPopup = null;

    public Context mContext;
    protected View baseView;
    protected PopupWindow mPopupWindow;
    protected Dialog mDialog;
    protected WindowManager.LayoutParams wmDParams = null;
    DisplayMetrics mDisplayMetrics = new DisplayMetrics();
    Display mDisplay;
    WindowManager wm;
    LayoutInflater layoutInflater;

    public BaseDialog(Context context) {
        mContext = context;
        if (sCurrentShowPopup != null && dismissOthers() && sCurrentShowPopup.isShowing()) {
            sCurrentShowPopup.dismiss();
            sCurrentShowPopup = null;
        }
    }

    protected abstract void initView(View view);

    protected abstract int getLayoutResId();

    public View getContentView() {
        View view = LayoutInflater.from(mContext).inflate(getLayoutResId(), null);
        initView(view);
        return view;
    }

    public void show() {
        baseView = getContentView();
        mDialog = new Dialog(mContext, R.style.FullHeightDialog);
        wmDParams = mDialog.getWindow().getAttributes();
        wmDParams.x = BoardUtil.dip2px(10);
        wmDParams.y = BoardUtil.dip2px(15);
        wmDParams.format = 1;
        mDialog.setContentView(baseView);
        mDialog.getWindow().setAttributes(wmDParams);
        mDialog.getWindow().setGravity(Gravity.RIGHT | Gravity.BOTTOM);
        mDialog.getWindow().setType(2002);
        mDialog.setCanceledOnTouchOutside(true);
        mDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                dowhenDismiss();
            }
        });
        mDialog.show();
        sCurrentShowPopup = this;
    }

    public void dowhenDismiss() {
        //用于子类用
    }

    public boolean isShowing() {
        return mDialog != null && mDialog.isShowing();
    }

    public void dismiss() {
        if (null != mDialog) mDialog.dismiss();
    }

    protected void setClickListener(final View view) {
        view.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                onViewClick(arg0);
                dismiss();
            }
        });
    }

    protected void onViewClick(View view) {
    }

    /**
     * 打開該Dialog,是否消滅掉前一個
     * @return
     */
    public boolean dismissOthers() {
        return true;
    }

}
